package dao

import (
	"go_server/game_server/database/mysql"
	"go_server/game_server/util"
	"go_server/zinx/zlog"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type BuildUpgrade struct {
	Id          string `gorm:"column:Id;primary"`
	UpgradeTime int64  `gorm:"column:upgrade_time"`
}

func (BuildUpgrade) TableName() string {
	return "build_upgrade"
}

var (
	all_build_upgrade_field = util.GetGormFields(BuildUpgrade{})
)

func GetBuildUpgradeByKey(key string) *BuildUpgrade {
	db := mysql.GetServerDBConnection()
	var buildUpgrade BuildUpgrade
	if err := db.Select(all_build_upgrade_field).Where("id=?", key).First(&buildUpgrade).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetBuildUpgradeByKey ERR!!! id: %s, err: %v", key, err)
		}
		return nil
	}
	return &buildUpgrade
}


func NewOrUpdateBuildUpgrade(key string, upgradeTime int64) {
	buildObj := &BuildUpgrade{
		Id:          key,
		UpgradeTime: upgradeTime,
	}

	db := mysql.GetServerDBConnection()
	if err := db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "id"}},
		DoUpdates: clause.AssignmentColumns([]string{"upgrade_time"}),
	}).Create(buildObj).Error; err != nil {
		zlog.Errorf("create or update BuildUpgrade %v data failed: %v", buildObj, err)
	}
}
